package com.dehui.traders.ui.buysell;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.TextAppearanceSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.dehui.traders.BR;
import com.dehui.traders.R;
import com.dehui.traders.bean.BaseListResponse;
import com.dehui.traders.bean.OptionalCodeRank;
import com.dehui.traders.bean.RealtimeQuote;
import com.dehui.traders.config.Preferences;
import com.dehui.traders.databinding.FragmentBuySellBinding;
import com.dehui.traders.kchart.DataParse;
import com.dehui.traders.kchart.KLineManager;
import com.dehui.traders.kchart.MyCombinedChart;
import com.dehui.traders.service.CallListener;
import com.dehui.traders.service.NetImpl;
import com.dehui.traders.ui.base.AppFragment;
import com.dehui.traders.ui.OptionHelper;
import com.dehui.traders.utils.ThreadTask;
import com.dehui.traders.widgets.ChartLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.goldze.mvvmhabit.utils.Utils;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by hqq on 18.4.4.
 */

public class BuySellFragment extends AppFragment<FragmentBuySellBinding,BuySellViewModel> {

    private BuySellViewModel viewModel;
    private List<RealtimeQuote> mList = new ArrayList<>();
    private boolean isLoadFirst = false;
    private int openK = 0;
    private String mCurrentMarket;
    private String mCurrentCode;
    private Map<String,List<String[]>> mMap = new HashMap<>();
    public List<String[]> mKList = new ArrayList<>();
    private DataParse mData;
    private MyCombinedChart mChartKline;
    private MyCombinedChart mChartVolume;
    private ProgressBar mProgressBar;
    private LinearLayout mLlk;

    @Override
    public int initContentView() {
        return R.layout.fragment_buy_sell;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public BuySellViewModel initViewModel() {
        viewModel = new BuySellViewModel(getContext());
        return viewModel;
    }

    @Override
    public void initData() {
        super.initData();
        initToolbarValue(R.string.buy_and_sell);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initViews();
        getNetData();
    }

    private void getNetData() {
        String myOpitonCode = Preferences.getMyOpitonCode();
        try {
            List<OptionalCodeRank> codeList =new Gson().fromJson(myOpitonCode, new TypeToken<List<OptionalCodeRank>>() {}.getType());
            searchRealTime(codeList);
        }catch (Exception e){

        }
    }

    /**
     * 查询实时分笔数据
     * @param list
     */
    private void searchRealTime(List<OptionalCodeRank> list) {
        Call<BaseListResponse<RealtimeQuote>> call = NetImpl.getRealtimeQuote(list);
        call.enqueue(new CallListener<BaseListResponse<RealtimeQuote>>() {
            @Override
            public void _onResponse(Response<BaseListResponse<RealtimeQuote>> response) {
                binding.refreshView.setRefreshing(false);
                BaseListResponse<RealtimeQuote> realtimeQuoteBaseListResponse = response.body();
                if (realtimeQuoteBaseListResponse.status == 200){
                    List<RealtimeQuote> realtimeQuoteList = realtimeQuoteBaseListResponse.result;
                    mList.clear();
                    mList.addAll(realtimeQuoteList);
                    initContainer();
                }
            }

            @Override
            public void _onFailure() {
                binding.refreshView.setRefreshing(false);
            }
        });
    }


    private void getCacheData() {
        List<RealtimeQuote> realtimeQuoteList = OptionHelper.getCacheOptionRealTime(getContext());
        if (realtimeQuoteList != null){
            mList.clear();
            mList.addAll(realtimeQuoteList);
            initContainer();
        }
    }

    private void initViews() {
        viewModel.refreshOptionData();

        binding.refreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getNetData();
            }
        });
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1){
                if (getActivity() == null || getActivity().isFinishing())
                    return;
                mProgressBar.setVisibility(View.GONE);
                mLlk.setVisibility(View.VISIBLE);
                KLineManager.getInstange().initKLine(getContext(),mChartKline,mChartVolume, mData);
            }
        }
    };

    private void initContainer() {
        binding.llContainer.removeAllViews();
        for (int i = 0; i < mList.size(); i++){

            View child = LayoutInflater.from(getContext()).inflate(R.layout.list_item_buy_and_sell, null);
            TextView tvName = child.findViewById(R.id.tv_name);
            TextView tvNew = child.findViewById(R.id.tv_new);
            TextView tvZhangfu = child.findViewById(R.id.tv_zhangfu);
            TextView tvZhangDie = child.findViewById(R.id.tv_zhangdie);
            LinearLayout llData = child.findViewById(R.id.ll_data);
            LinearLayout llK = child.findViewById(R.id.ll_k);
            MyCombinedChart chartKline = child.findViewById(R.id.mycombinedchart_k_line);
            MyCombinedChart chartVolume = child.findViewById(R.id.mycombinedchart_k_volume);
            ChartLayout rlK = child.findViewById(R.id.rl_k);
            ProgressBar progressBar = child.findViewById(R.id.progressbar);

            RealtimeQuote item = mList.get(i);

            String title = item.name + "\n" + item.code;
            SpannableString styledText = new SpannableString(title);
            styledText.setSpan(new TextAppearanceSpan(getContext(), R.style.style_title_0), 0, item.name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            styledText.setSpan(new TextAppearanceSpan(getContext(), R.style.style_title_1), item.name.length(), title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            tvName.setText(title,TextView.BufferType.SPANNABLE);

            tvNew.setText(Utils.doubleToString(item.price));
            tvNew.setTextColor(Color.RED);

            float s = (item.price - item.openPrice) / item.openPrice;
            tvZhangfu.setText(Utils.doubleToString(s) + "%");
            if (item.price - item.openPrice > 0){
                tvZhangfu.setTextColor(Color.RED);
            }else if (item.price - item.openPrice < 0){
                tvZhangfu.setTextColor(Color.GREEN);
            }else {
                tvZhangfu.setTextColor(Color.WHITE);
            }

            tvZhangDie.setText(Utils.doubleToString(item.price - item.openPrice));
            if (item.price - item.openPrice > 0){
                tvZhangDie.setTextColor(Color.RED);
            }else if (item.price - item.openPrice < 0){
                tvZhangDie.setTextColor(Color.GREEN);
            }else {
                tvZhangDie.setTextColor(Color.WHITE);
            }

            if (openK == i){
                rlK.setVisibility(View.VISIBLE);
                mChartKline = chartKline;
                mChartVolume = chartVolume;
                mLlk = llK;
                mProgressBar = progressBar;

                String myOpitonCode = Preferences.getMyOpitonCode();
                List<OptionalCodeRank> codeList =new Gson().fromJson(myOpitonCode, new TypeToken<List<OptionalCodeRank>>() {}.getType());
                try {
                    mCurrentMarket = codeList.get(i).market;
                }catch (Exception e){

                }
                mCurrentCode = item.code;

                mProgressBar.setVisibility(View.VISIBLE);
                List<String[]> list = mMap.get(mCurrentCode);
                if (list == null){
//                    List<String[]> kLines = OptionHelper.getKLine(getContext(), mCurrentCode);
//                    if (kLines != null){
//                        setKLine(kLines);
//                    }
                    getHistoryRiK(progressBar,llK);
                }else{
                    setKLine(list);
                }


            }else{
                rlK.setVisibility(View.GONE);
            }

            int finalI = i;
            llData.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openK = finalI;
                    initContainer();
                }
            });
            binding.llContainer.addView(child);
        }
        binding.refreshView.refresh();
    }

    private void getHistoryRiK(ProgressBar progressBar, LinearLayout llK) {
        Call<BaseListResponse<String[]>> call = NetImpl.getKBussinessLabelPoint(mCurrentMarket + mCurrentCode);
        call.enqueue(new CallListener<BaseListResponse<String[]>>() {
            @Override
            public void _onResponse(Response<BaseListResponse<String[]>> response) {
                BaseListResponse<String[]> baseListResponse = response.body();
                if (baseListResponse.status == 200){
                    List<String[]> list = baseListResponse.result;
                    Collections.reverse(list);
                    mKList.clear();
                    mKList.addAll(list);
                    mMap.put(mCurrentCode,mKList);
                    setKLine(list);
                    getTodayRiK();
                }
            }

            @Override
            public void _onFailure() {
                progressBar.setVisibility(View.GONE);
            }
        });
    }

    private void getTodayRiK() {
        Call<BaseListResponse<String[]>> call = NetImpl.getKBussinessLabelPoint(mCurrentMarket + mCurrentCode);
        call.enqueue(new CallListener<BaseListResponse<String[]>>() {
            @Override
            public void _onResponse(Response<BaseListResponse<String[]>> response) {
                if (getActivity() == null || getActivity().isFinishing())
                        return;
                BaseListResponse<String[]> baseListResponse = response.body();
                if (baseListResponse.status == 200){
                    List<String[]> list = baseListResponse.result;
                    Collections.reverse(list);
                    mKList.addAll(list);
                    mMap.put(mCurrentCode,mKList);
                    setKLine(mKList);
                }
            }

            @Override
            public void _onFailure() {

            }
        });
    }

    private void setKLine(List<String[]> kLines) {
        if (mData == null){
            mData = new DataParse();
        }
        ThreadTask.getInstance().executorOtherThread(new Runnable() {
            @Override
            public void run() {
                mData.parseKLineBS(kLines,true);
                mHandler.sendEmptyMessage(1);
            }
        },10);

    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isLoadFirst){
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    getCacheData();
                    isLoadFirst = true;
                }
            },200);
        }
    }


}
